package com.pureut.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysRole;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.domain.*;
import com.pureut.system.domain.dto.SupplierListDetailsDto;
import com.pureut.system.domain.dto.SupplierListPageDto;
import com.pureut.system.domain.vo.SupplierListVo;
import com.pureut.system.export.SupplierExport;
import com.pureut.system.export.UserExport;
import com.pureut.system.mapper.SupplierAccessMapper;
import com.pureut.system.mapper.SupplierListMapper;
import com.pureut.system.mapper.SupplierPerformanceMapper;
import com.pureut.system.mapper.SysUserMapper;
import com.pureut.system.service.ISupplierAccessService;
import com.pureut.system.service.ISupplierListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * @Author: pureut
 * @Date: 2024-12-05 17:16:19
 * @Desc: 供应商名录
 */
@Service("supplierListService")
public class SupplierListServiceImpl extends ServiceImpl<SupplierListMapper, SupplierList> implements ISupplierListService {

    /**
     * 供应商名录Dao
     */
    @Resource
    private SupplierListMapper supplierListMapper;



    /**
     * 供应商准入Dao
     */
    @Resource
    private SupplierAccessMapper supplierAccessMapper;

//
    /**
     * 供应商绩效Dao
     */
    @Resource
    private SupplierPerformanceMapper supplierPerformanceMapper;

    @Resource
    SysUserMapper userMapper;

    /**
     * 查询列表
     * @param supplierListVo
     * @return
     */
    @Override
    public List<SupplierListPageDto> queryPage(SupplierListVo supplierListVo) {
        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierListPageDto> supplierListPageDtos = supplierListMapper.selectByPage(supplierListVo);
        supplierListPageDtos.forEach(e->{
            e.setSupplierCategory(netMap.get(String.valueOf(e.getSupplierCategory())));
            e.setTransactionType(netMap2.get(String.valueOf(e.getTransactionType())));
            e.setSupplierLevel(netMap3.get(String.valueOf(e.getSupplierLevel())));
        });

        return supplierListPageDtos;
    }


    /**
     * 新增供应商名录
     * @param supplierListVo
     * @return
     */
    @Override
    public Boolean save(SupplierListVo supplierListVo) {
        SupplierList supplierList = new SupplierList();
        BeanUtil.copyProperties(supplierListVo, supplierList);
        supplierList.setCreateBy(SecurityUtils.getUsername());
        supplierList.setCreateTime(new Date());
        return save(supplierList);
    }


    /**
     * 更新供应商名录
     * @param supplierListVo
     * @return
     */
    @Override
    public Boolean updateById(SupplierListVo supplierListVo) {
        SupplierList supplierList = new SupplierList();
        BeanUtil.copyProperties(supplierListVo, supplierList);
        supplierList.setUpdateBy(SecurityUtils.getUsername());
        supplierList.setUpdateTime(new Date());
        return updateById(supplierList);
    }

    @Override
    public SupplierListDetailsDto getInfoById(Long id){
        SupplierListDetailsDto supplierListDetailsDto=new SupplierListDetailsDto();
        SupplierList byId = getById(id);
        BeanUtil.copyProperties(byId, supplierListDetailsDto);
        if(ObjectUtil.isNotNull(byId.getAdmittanceId())){
            supplierListDetailsDto.setSupplierAccessDeails(supplierAccessMapper.getInfoById(byId.getAdmittanceId()));
        }
        supplierListDetailsDto.setSupplierPerformance(supplierPerformanceMapper.getInfoBySuId(id));
        return supplierListDetailsDto;
    }

    /**
     * 供应商信息导出
     * @param supplierListVo
     * @return
     */
    @Override
    public List<SupplierListPageDto> getInfoExport(SupplierListVo supplierListVo)
    {
        if (supplierListVo.getIdStr() != null) {

            List<String> idList = Arrays.asList(supplierListVo.getIdStr().split(","));

            supplierListVo.setIds(idList);
        }

        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SupplierListPageDto> supplierListPageDtos = supplierListMapper.selectByPage(supplierListVo);
        supplierListPageDtos.forEach(e->{
            e.setSupplierCategory(netMap.get(String.valueOf(e.getSupplierCategory())));
            e.setTransactionType(netMap2.get(String.valueOf(e.getTransactionType())));
            e.setSupplierLevel(netMap3.get(String.valueOf(e.getSupplierLevel())));
        });

        return supplierListPageDtos;
    }

    /**
     * 供应商导入
     * @param coCustomer
     * @return
     */
    @Override
    public String importMouldData(List<SupplierExport> coCustomer)
    {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入供应商信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 获取认证方式的数据字典
        List<SysDictData> netArray = DictUtils.getDictCache("supplier_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        // 获取认证方式的数据字典
        List<SysDictData> netArray2 = DictUtils.getDictCache("transaction_type");
        Map<String, String> netMap2 = netArray2.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
        // 获取认证方式的数据字典
        List<SysDictData> netArray3 = DictUtils.getDictCache("supplier_grade");
        Map<String, String> netMap3 = netArray3.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));


        for (SupplierExport supplierExport : coCustomer) {
            SupplierList supplierList = new SupplierList();
            try {

                //供应商编码
                supplierList.setSupplierCode(supplierExport.getSupplierCode());
                //供应商名称
                supplierList.setSupplierName(supplierExport.getSupplierName());
                supplierList.setSupplierCategory(netMap.get(String.valueOf(supplierExport.getSupplierCategory())));
                supplierList.setTransactionType(netMap2.get(String.valueOf(supplierExport.getTransactionType())));
                supplierList.setSupplierLevel(netMap3.get(String.valueOf(supplierExport.getSupplierLevel())));
                supplierList.setContactPerson(supplierExport.getContactPerson());
                supplierList.setContactInfo(supplierExport.getContactInfo());
                supplierList.setSupplierAddress(supplierExport.getSupplierAddress());

                boolean save = save(supplierList);

                if (!save) {
                    throw new GlobalException("导入失败");
                }

                successNum++;
                successMsg.append(successNum).append("、供应商信息 ").append(supplierList.getSupplierName()).append(" 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、供应商信息 " + supplierList.getSupplierName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    /**
     * 查看供应商变更历史
     * @param supplierId
     * @return
     */
    @Override
    public List<ChangeApplication> getAlterHistoryList(String supplierId)
    {
        return supplierListMapper.getAlterHistoryList(supplierId);
    }

    /**
     * 保存供应商变更
     * @param changeApplication
     * @return
     */
    @Override
    public int saveChangeApplication(ChangeApplication changeApplication)
    {
        return supplierListMapper.saveChangeApplication(changeApplication);
    }

    /**
     * 修改变更信息
     */
    @Override
    public int updateSupplierHis(SupplierAlterHistory supplierAlterHistory)
    {
        SupplierList supplierList = supplierListMapper.selectOne(new QueryWrapper<SupplierList>().lambda().eq(SupplierList::getId, supplierAlterHistory.getSupplierId()));
        BeanUtil.copyProperties(supplierAlterHistory,supplierList);
        updateById(supplierList);

        //插入历史表
        return supplierListMapper.insertHis(supplierAlterHistory);
    }

    /**
     * 获取变更之前的供应商信息
     * @param supplierAlterHistory
     * @return
     */
    @Override
    public SupplierList getBeforeSuppler(SupplierAlterHistory supplierAlterHistory)
    {
        SupplierList supplierList = supplierListMapper.selectOne(new QueryWrapper<SupplierList>().lambda().eq(SupplierList::getId, supplierAlterHistory.getSupplierId()));
        return supplierList;
    }

    /**
     * 供应商索赔
     * @param compensationApplication
     * @return
     */
    @Override
    public int supplierClaim(CompensationApplication compensationApplication)
    {
        return supplierListMapper.supplierClaim(compensationApplication);
    }
}
